﻿
using System;
using System.IO;
using System.Xml.Serialization;

namespace AnOtherBlog.Core.Extensions
{
	/// <summary>
	/// Extensions to serialize and deserialize any objects in C# 3.0
	/// Warning, objects to be serialized need a constructor without parameters
	/// 
	/// This only work with C# 3.0, it have the ability to extend types
	/// 
	/// </summary>
	public static class XmlConvertExtensions
	{
		/// <summary>
		/// Serialize any object that have a constructor without parameters
		/// </summary>
		/// <param name="obj"></param>
		/// <returns>A string in XML format having all properties and values for the object</returns>
		public static String ToXml(this object obj)
		{
			XmlSerializer s = new XmlSerializer(obj.GetType());
			using (StringWriter writer = new StringWriter())
			{
				s.Serialize(writer, obj);
				return writer.ToString();
			}
		}
		/// <summary>
		/// Deserialize a previous serialized object
		/// </summary>
		/// <typeparam name="T">typeof object to deserialize</typeparam>
		/// <param name="data">string in XML format having properties and values for the object</param>
		/// <returns>Reference to the object</returns>
		public static T ConvertTo<T>(this string data)
		{
			XmlSerializer s = new XmlSerializer(typeof(T));
			using (StringReader reader = new StringReader(data))
			{
				object obj = s.Deserialize(reader);
				return (T)obj;
			}
		}
	}
}
